/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops;

import java.util.Map;
import java.util.Map.Entry;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mobaas.devops.HostMonitor;
import com.mobaas.devops.Notifier;
import com.mobaas.devops.VcsProvider;
import com.mobaas.devops.schedule.DefaultTaskScheduler;

/**
 * 
 * @author billy zhang
 * 
 */
@Configuration
@ConfigurationProperties(prefix = "devops.component")
public class ComponentConfig {

	private Map<String, String> hostMonitor;
	private Map<String, String> vcsProvider;
	private Map<String, String> notifier;
	private Map<String, String> healthChecker;
	
	public void setHostMonitor(Map<String, String> hostMonitor) {
		this.hostMonitor = hostMonitor;
	}

	public void setVcsProvider(Map<String, String> vcsProvider) {
		this.vcsProvider = vcsProvider;
	}

	public void setNotifier(Map<String, String> notifier) {
		this.notifier = notifier;
	}
	
	public void setHealthChecker(Map<String, String> healthChecker) {
		this.healthChecker = healthChecker;
	}
	
	@Bean
	public TaskSchedulerFactory taskSchedulerFactory() {
		TaskSchedulerFactory factory = new TaskSchedulerFactory();
		factory.setScheduler(defaultTaskScheduler());
		
		return factory;
	}
	
	@Bean
	public DefaultTaskScheduler defaultTaskScheduler() {
		return new DefaultTaskScheduler();
	}
	
	@Bean
	public ComponentFactory<HostMonitor> hostMonitorFactory() {
		
		return createComponentFactory( hostMonitor );
	}
	
	@Bean
	public ComponentFactory<VcsProvider> vcsProviderFactory() {
		
		return createComponentFactory(vcsProvider);
		
	}
	
	@Bean
	public ComponentFactory<Notifier> notifierFactory() {
		
		return createComponentFactory(notifier);
		
	}
	
	@Bean
	public ComponentFactory<HealthChecker> healthCheckerFactory() {
		
		return createComponentFactory(healthChecker);
		
	}
	
	private <T> ComponentFactory<T> createComponentFactory(Map<String, String> map) {
		ComponentFactory<T> factory = new ComponentFactory<>();
		
		for (Entry<String, String> entry : map.entrySet()) {
			try {
				Class<? extends T> clazz = (Class<? extends T>) Class.forName(entry.getValue());
				factory.register(entry.getKey(), clazz);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		return factory;
	}
}
